<?php

namespace App\Http\Model;

use App\Server\Helper;
use Faker\Provider\tr_TR\DateTime;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //
    protected $table = 'htf_user';
    public $timestamps = false;
    protected $guarded=[];

    /**
     * 绑定用户信息
     * @param $mobile
     * @param $openId
     * @param $nickName
     * @param $pic
     * @param $email
     * @param $unionid
     * @return bool
     * create by wenQing
     */
    public function bindUser($mobile,$openId,$nickName,$pic,$email,$unionid)
    {
        //判断一下用户是否已经注册了，如果没有进行用户的注册;如果注册了，直接更新openid就可以了
        $user = User::where('username',$mobile)->get();
        if(!$user->isEmpty())
        {
            $re = User::where('username',$mobile)->update(['open_id'=>$openId]);
        }
        else
        {
            $rand = rand(100000,999999); //产生一个6位的随机数，作为用户的密码
            $this->username = $mobile;
            $this->auth_key = time();
            $this->password_hash = md5($rand.time());
            $this->email = $email;
            $this->sex = 0;
            $this->nic_thumb = $pic;
            $this->nic_name = $nickName;
            $this->open_id = $openId;
            $this->unionid = $unionid; //开发平台的unionid，唯一标示
            $this->create_time = date('Y-m-d H:i:s');
            $re = $this->save();

            //发送注册用户的短信提示
            $msgRe = Helper::send_post(env('API_PRE').'send_wechat_register_msg',['mobile'=>$mobile,'code'=>$rand]);
            if($msgRe['status'] == '0') return back()->with('msg','验证码发送失败！');
        }
        return $re;
    }

    /**
     * 微信登录
     * @param $username
     * @return string
     * create by wenQing
     */
    public function login($username)
    {
        $postData = [
            'device' => 'wap',
            'username' => $username,
            'code' => md5($username.'haotoufa')
        ];
        $re = Helper::send_post(env('API_PRE').'wechat_login',$postData);
        if(empty($re)) return back()->with('msg','获取用户信息失败，检查接口服务器');

        return $re;
    }
}
